import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { List, Card, Input, Button, Modal, Form } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Result from '@/components/Result';
import moment from 'moment';
import styles from './Order.less';

const FormItem = Form.Item;

@connect(({ order, loading }) => ({
  order,
  loading: loading.models.list,
}))
@Form.create()
class Order extends PureComponent {
  state = {
    visible: false,
    done: false,
    editableIndex: '',
  };

  formLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 13 },
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/fetch',
    });
  }

  showModal = () => {
    this.setState({
      visible: true,
      current: undefined,
    });
  };

  showEditModal = (item, index) => {
    this.setState({
      visible: true,
      current: item,
      editableIndex: index,
    });
  };

  handleDone = () => {
    this.setState({
      done: false,
      visible: false,
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { current, editableIndex } = this.state;
    const id = current ? current.id : '';
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        done: true,
      });
      dispatch({
        type: 'order/update',
        payload: {
          ...fieldsValue,
          id,
          editableIndex,
        },
      });
    });
  };

  render() {
    const {
      order: { data },
      loading,
    } = this.props;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { visible, done, current = {} } = this.state;
    const modalFooter = done
      ? { footer: null, onCancel: this.handleDone }
      : { okText: '保存', onOk: this.handleSubmit, onCancel: this.handleCancel };

    const ListContent = ({
      data: {
        receiverName,
        price,
        remark,
        expressNumber,
        expressageName,
        receiverAddress,
        receiverPhone,
        status,
        createdAt,
      },
    }) => (
      <div className={styles.listContent}>
        <div className={styles.listContentItem}>
          <span>金额</span>
          <p>{price / 100}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>快递名称</span>
          <p>{expressageName || '暂无'}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>快递单号</span>
          <p>{expressNumber || '暂无'}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>收货人</span>
          <p>{receiverName || '暂无'}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>收货地址</span>
          <p>{receiverAddress || '暂无'}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>收货电话</span>
          <p>{receiverPhone || '暂无'}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>备注</span>
          <p>{remark || '暂无'}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>下单时间</span>
          <p>{moment(createdAt).format('YYYY-MM-DD hh:mm:ss') || '暂无'}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>订单状态</span>
          <p>
            {status === 'shipment' ? '送货中' : ''}
            {status === 'unpaid' ? '未支付' : ''}
            {status === 'paid' ? '已支付' : ''}
            {status === 'completed' ? '已完成' : ''}
          </p>
        </div>
      </div>
    );

    const getModalContent = () => {
      if (done) {
        return (
          <Result
            type="success"
            title="操作成功"
            description="已确认添加该图片"
            actions={
              <Button type="primary" onClick={this.handleDone}>
                知道了
              </Button>
            }
            className={styles.formResult}
          />
        );
      }
      // const imageUrl = this.state.imageUrl;
      return (
        <Form onSubmit={this.handleSubmit}>
          <FormItem label="快递企业" {...this.formLayout}>
            {getFieldDecorator('expressageName', {
              rules: [{ required: true, message: '请输入快递企业', max: 12 }],
              initialValue: current.expressageName,
            })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem label="快递单号" {...this.formLayout}>
            {getFieldDecorator('expressNumber', {
              rules: [{ required: true, message: '请输入快递单号', max: 30 }],
              initialValue: current.expressNumber,
            })(<Input placeholder="请输入" />)}
          </FormItem>
        </Form>
      );
    };
    return (
      <PageHeaderWrapper>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title="订单管理"
            style={{ marginTop: 24 }}
            bodyStyle={{ padding: '0 32px 40px 32px' }}
          >
            <List
              size="large"
              rowKey="id"
              loading={loading}
              pagination={{
                ...data.pagination,
                onChange: page => {
                  const { dispatch } = this.props;
                  dispatch({
                    type: 'order/fetch',
                    payload: page,
                  });
                },
              }}
              dataSource={data.list.filter(item => item.status !== 'unpaid')}
              item={data.list}
              renderItem={(item, index) => (
                <List.Item
                  actions={[
                    <a
                      onClick={e => {
                        e.preventDefault();
                        this.showEditModal(item, index);
                      }}
                    >
                      {item.status !== 'completed' ? '发货' : ''}
                    </a>,
                  ]}
                >
                  <List.Item.Meta title={`[${item.id}] ${item.title}`} description={item.intro} />
                  <ListContent data={item} />
                </List.Item>
              )}
            />
          </Card>
        </div>
        <Modal
          title={done ? null : `订单管理`}
          className={styles.standardListForm}
          width={640}
          bodyStyle={done ? { padding: '72px 0' } : { padding: '28px 0 0' }}
          destroyOnClose
          visible={visible}
          {...modalFooter}
        >
          {getModalContent()}
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default Order;
